﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace FanaticGene.AvaloniaMaid.Core
{
    ///<summary>Avalonia 档案工厂</summary>
    internal class AvaloniaArchiveFactory
    {



        public void LoadXamlFiles(AvaloniaArchive archive)
        {
            var dirPath = GetArchiveMainPath(archive.ArchivePath);
            var files = archive.ControlThemes._resourceFiles;
            var xamls = Directory.GetFiles(dirPath, "*.xaml", SearchOption.AllDirectories);
            //files.AddRange(xamls);

            var includeList = GetIncludeList();

            foreach (var file in xamls)
            {
                var fileName = Path.GetFileNameWithoutExtension(file);
                var relativePath = file.Substring(dirPath.Length + 1);
                if (IsIncludePath(relativePath, includeList) == false) continue; 
                files.Add(new CodeUri() { FullPath = file, Name = fileName, ReleativePath = relativePath });
            }
        }

        private IEnumerable<string> GetIncludeList()
        {
            return new[] { "src" };
        }

        private bool IsIncludePath(string path, IEnumerable<string> includes)
        {
            foreach (var include in includes)
            {
                if (path.StartsWith(include, StringComparison.OrdinalIgnoreCase)) return true;
            }
            return false;
        }

        private string GetArchiveMainPath(string path)
        {
            var subDirs = Directory.GetDirectories(path);
            if (subDirs.Length == 1) return subDirs[0];
            return path;
        }

    }
}
